package com.friendfeed.api;

import java.text.ParseException;
import java.util.Date;
import java.util.Collection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.InputStream;
import java.io.IOException;

public class FriendFeedUtils {
	
	public static final String DATE_PATTERN = "yyyy-MM-dd'T'HH:mm:ss'Z' zzz";
	
    private static final ThreadSafeSimpleDateFormat sdf = new ThreadSafeSimpleDateFormat(DATE_PATTERN, 5, 20, false);

    public static Date parseDate(String date) throws ParseException {
        if (date == null || "".equals(date)) {
            return null;
        }

        try {
            Date d = sdf.parse(date + " UTC");
            return d;
        } catch (Exception e) {
            return null;
        }
    }

    public static String join(Collection<? extends Object> c, String separator) {
        StringBuilder sb = new StringBuilder();
        for (Object o : c) {
            sb.append(o).append(separator);
        }
        sb.deleteCharAt(sb.length() - 1);

        return sb.toString();
    }

    public static void writeInputStream(InputStream ss, StringBuilder sb) throws IOException {
        byte[] buffer = new byte[2048];
        int length;
        while ((length = ss.read(buffer)) != -1) {
            sb.append(new String(buffer, 0, length));
        }
        ss.close();
    }
    
    public static boolean isImgTag(String s)
    {
    	if (s == null)
    	{
    		return false;
    	}
    	else 
    	{
    		s = s.trim();
    		return (s.startsWith("<img") || s.startsWith("<IMG"));
    	}
    	
    }
    
    public static String getUrlFromImgTag(String imgTag)
    {
    	String url = null;
    	
		Pattern p = Pattern.compile("src='[^']*'", Pattern.CASE_INSENSITIVE);
		Matcher m = p.matcher(imgTag);
		if (m.find())
		{
			url = imgTag.substring(m.start() + 5, m.end() - 1);
		}
		
		return url;
   }
}
